package com.aisafer.fms.storage;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.aisafer.fms.client.dto.AuthReq;
import com.aisafer.fms.client.dto.DeleteReq;
import com.aisafer.fms.client.dto.DownReq;
import com.aisafer.fms.client.enums.StorageTypeEnums;
import com.aisafer.fms.domain.Attachment;
import com.aisafer.fms.domain.AttachmentE;
import com.aisafer.fms.domain.Module;
import com.aisafer.fms.domain.StsConfig;
import com.aisafer.fms.enums.AttachmentStatusEnums;
import com.aisafer.fms.exception.LocalException;
import com.aisafer.fms.mapper.AttachmentEMapper;
import com.aisafer.fms.mapper.AttachmentMapper;
import com.aisafer.fms.mapper.ModuleMapper;
import com.aisafer.fms.mapper.StsConfigMapper;
import com.aisafer.fms.service.IStorageManager;
import com.aisafer.fms.service.impl.AttachmentService;
import com.aliyun.oss.ServiceException;
import com.polaris.base.ftp.FTPUtils;
import com.polaris.base.ftp.SFTP;

/**
 * 本地存储
 * 
 * @author stevin
 *
 */
@Service("FTP")
public class FTP extends AbstractStorage implements IStorageManager {

	private static final Logger log = LoggerFactory.getLogger(FTP.class);

	@Autowired
	private AttachmentService attachmentService;

	@Autowired
	protected AttachmentEMapper attachmentEDao;

	@Autowired
	protected AttachmentMapper attachmentDao;

	@Autowired
	private ModuleMapper moduleDao;
	
	@Autowired
	private StsConfigMapper stsConfigDao;
	
	@Autowired
	ModuleMapper moduleMapper;

	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
	public void upload(AttachmentE attachmentE, byte[] content) {
		try {
			log.info("ftpPath:{},attachid:{}",  attachmentE.getStorageKey(),
					attachmentE.getAttachid());
			attachmentService.saveAttach(attachmentE, StorageTypeEnums.FTP, AttachmentStatusEnums.SUCCESS);
			save(attachmentE, content);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new LocalException(e.getMessage());
		}
	}

	private void save(AttachmentE attachmentE, byte[] content) throws IOException {
		if(content == null || content.length <=0) {
			return;
		}
		FTPUtils sftp = null;
		try {
			Attachment attachment = attachmentDao.selectByPrimaryKey(attachmentE.getAttachid());
			if (attachment == null) {
				return;
			}
			
			Module moduleObj = moduleMapper.selectByPrimaryKey(attachment.getModuleId());
			StsConfig sts = new StsConfig();
			sts.setModuleId(moduleObj.getId());
			sts.setStorageMode(StorageTypeEnums.FTP.name());
			StsConfig stsConfig = stsConfigDao.select(sts);
			
			
			SFTP ftp = new SFTP();
			ftp.setHost(stsConfig.getAddress());
			ftp.setPassword(stsConfig.getPassword());
			ftp.setPort(stsConfig.getPort());
			ftp.setUserName(stsConfig.getUsername());
			sftp = new FTPUtils(ftp);
			sftp.uploadFile(stsConfig.getDirectory(), attachmentE.getStorageKey(), new ByteArrayInputStream(content));
		} catch(Exception e){
			log.error(e.getMessage());
		}
	}

	@Override
	public byte[] read(DownReq atte) {
		FTPUtils sftp = null;
		try {
			Attachment attachment = attachmentDao.selectByPrimaryKey(atte.getAttachid());
			if (attachment == null) {
				return null;
			}
			Module moduleObj = moduleMapper.selectByPrimaryKey(attachment.getModuleId());
			StsConfig sts = new StsConfig();
			sts.setModuleId(moduleObj.getId());
			sts.setStorageMode(StorageTypeEnums.FTP.name());
			StsConfig stsConfig = stsConfigDao.select(sts);
			
			SFTP ftp = new SFTP();
			ftp.setHost(stsConfig.getAddress());
			ftp.setPassword(stsConfig.getPassword());
			ftp.setPort(stsConfig.getPort());
			ftp.setUserName(stsConfig.getUsername());
			sftp = new FTPUtils(ftp);
			return sftp.downloadFile(stsConfig.getDirectory(), atte.getStorageKey());
		} catch(Exception e){
			log.error(e.getMessage());
		}
		return null;
	}

	@Override
	public String getAuthUrl(AuthReq req) throws ServiceException {
		try {
			Module module = new Module();
			module.setModuleKey(req.getModulekey());
			Module moduleObj = this.moduleDao.select(module);
			final Map<String, Object> param = new HashMap<String, Object>();
			param.put("attachid", req.getAttachid());
			param.put("urlExpire", String.valueOf(getUrlExpire(req)));
			param.put("moduleKey",moduleObj.getModuleKey());
			param.put("timestamp", String.valueOf(System.currentTimeMillis()));
			if (req.getHeight() != null && req.getHeight() > 0 && req.getWidth() != null && req.getWidth() > 0) {
				param.put("height", req.getHeight());
				param.put("width", req.getWidth());
			}
	
			return null;
		}catch(Exception e) {
			log.error(e.getMessage());
		}
		return "";
	}

	private Long getUrlExpire(AuthReq req) {
		if (req.getUrlExpire() == null || req.getUrlExpire() <= 0) {
			return attachConfig.getUrlDefalutExpire();
		}
		return req.getUrlExpire();
	}


	@Override
	public boolean delete(DeleteReq req) {
	
		return false;
	}

}
